<template>
  <div>
    <!-- 表单部分 -->
    <el-form :model="formInline" :inline="true" class="demo-form-inline">
      <el-form-item label="单号">
        <el-input v-model="formInline.number" placeholder="请输入单据编号" clearable />
      </el-form-item>
      <el-form-item label="商品信息：">
        <el-input v-model="formInline.supName" placeholder="请输入商品信息" clearable />
      </el-form-item>
      <el-form-item label="单据日期">
        <el-date-picker v-model="formInline.date" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
          style="width: 280px; margin-left: 10px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadMenus">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格部分 -->
    <el-table :data="page.records" @selection-change="handleSelectionChange" style="width: 1450px">
      <el-table-column type="selection" width="50" />
      <el-table-column prop="erpSupplier.supName" label="会员" width="140" />
      <el-table-column prop="number" label="单据编号" width="170" />
      <el-table-column prop="erpDepotItemList[0].erpMaterial.material_name" label="商品信息" width="320" />
      <el-table-column prop="createTime" label="单据日期" width="170" />
      <el-table-column prop="erpUser.username" label="操作员" width="84" />
      <el-table-column prop="erpDepotItemList[0].operNumber" label="数量" width="82" />
      <el-table-column prop="erpDepotItemList[0].allPrice" label="金额合计" width="82" />
      <el-table-column prop="erpDepotItemList[0].taxLastMoney" label="含税金额" width="82" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="danger" effect="light">未审核</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="success" effect="light">已审核</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="warning" effect="light">已审核</el-tag>
          
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination v-model:page-size="page.size" v-model:current-page="page.current"
      @current-change="handleCurrentChange" @size-change="handleSizeChange" :page-sizes="[2, 4, 8, 10]"
      layout="total, sizes, prev, pager, next, jumper" :total="page.total" background style="margin-top:20px;">
    </el-pagination>

    <!-- 操作按钮部分 -->
    <div style="margin-top: 20px; text-align: right;">
      <el-button @click="close">取消</el-button>
      <el-button type="primary"
        @click="saveSelected({ cname: '单据明细', path: '/retail/retail_back/insert/documentdetails' }, page.records)">确定</el-button>
    </div>

    <!-- 对话框部分 -->
    <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="65%" top="15vh" style="height: 750px">
      <Documentdetails :key="data" :data="data" @closeAssociate="handleCloseAssociate" @close="close" @items="items" />
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, defineEmits } from 'vue';
import request from '@/api/request';
import { ElMessage } from 'element-plus';

import Documentdetails from './Documentdetails.vue';
let emits = defineEmits(['close','subdocument']);
// 响应式变量定义
const visible = ref(false);
const title = ref("");
const data = ref([]);
const page = ref({
  current: 1,
  size: 10,
  total: 0,
  records: []
});
const formInline = reactive({
  number: '',
  supName: '',
  date: ''
});
const selectedItems = ref([]);
// 响应式变量定义


// 关闭弹窗
const close = () => {
  emits("close");
};

// 处理分页变化
const handleCurrentChange = (val) => {
  page.value.current = val;
  loadMenus();
};

const handleSizeChange = (val) => {
  page.value.size = val;
  page.value.current = 1;
  loadMenus();
};

// 处理对话框关闭操作
const handleCloseAssociate = () => {
  visible.value = false; // 关闭 Associateorder
};


// 加载数据
// 加载数据
const loadMenus = () => {
  request({
    url: '/retail/findByPageAssociateorder',
    method: "get",
    params: {
      current: page.value.current,
      size: page.value.size,
      number: formInline.number,
      subType: '零售'
    }
  }).then(res => {
    // 获取当前请求的单据编号
    page.value.records = res.data.records;
    page.value.total = res.data.total;
    const numbers = page.value.records.map(record => record.number);
    console.log('单据编号:', numbers);
    
    // 加载第二组数据并进行对比
    loadMenus2(numbers);
  }).catch(err => {
    ElMessage.error('加载数据失败');
  });
};

// 加载数据并接收 numbers 进行对比
const loadMenus2 = (numbers) => {
  request({
    url: '/retail/selectLm', // 更新请求的 URL
    method: "get",
  }).then(res => {
    console.log('加载数据成功111:', res.data);
    const linkNumbers = res.data.map(record => record.linkNumber);
    console.log('linkNumber 值:', linkNumbers);
    
    // 对比 numbers 和 linkNumbers
    const inBoth = numbers.filter(number => linkNumbers.includes(number));
    console.log('在两个数组中都存在的编号:', inBoth);
    
    const onlyInNumbers = numbers.filter(number => !linkNumbers.includes(number));
    console.log('只在单据编号中存在的编号:', onlyInNumbers);
    
    const onlyInLinkNumbers = linkNumbers.filter(linkNumber => !numbers.includes(linkNumber));
    console.log('只在 linkNumber 中存在的编号:', onlyInLinkNumbers);
     // 根据在两个数组中存在的编号，找到对应的记录
      const defaultSelected = page.value.records.filter(record => inBoth.includes(record.number));
    console.log('默认选中的记录:', defaultSelected);

    // 如果有默认选中的记录，调用 handleSelectionChange 方法
    if (defaultSelected.length > 0) {
      handleSelectionChange(defaultSelected);
    }
  }).catch(err => {
    ElMessage.error('加载数据失败');
  });
};

// 初始化调用
loadMenus();





// 接收从 Documentdetails.vue 中的选中项
const items = (items) => {
  console.log('从 Documentdetails 接收到的选中项:', items);
  emits('subdocument', items,selectedItems.value); // 向父组件传递选中项
};

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedItems.value = val;
  console.log('选择变化:', selectedItems.value);
};

// 重置表单
const resetForm = () => {
  formInline.number = '';
  formInline.supName = '';
  formInline.date = '';
};

// 确定按钮处理
const saveSelected = (p, row) => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请至少选择一个商品');
    return;
  }
  const selectedData = selectedItems.value[0]; // 选中的数据
  title.value = p.cname;
  data.value = selectedData; // 将选中的数据传递给 Documentdetails
  visible.value = true; // 显示对话框
  console.log('选中的数据:', selectedData);
};

// 初始加载数据 
loadMenus();















</script>
